package com.sunhao.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.sunhao.common.constant.AuthServerConstant;
import com.sunhao.common.exception.BizCodeEnum;
import com.sunhao.common.utils.R;
import com.sunhao.common.vo.MemberRespVo;
import com.sunhao.gulimall.auth.feign.MemberFeignService;
import com.sunhao.gulimall.auth.feign.ThirdPartyFeignService;
import com.sunhao.gulimall.auth.vo.UserLoginVo;
import com.sunhao.gulimall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 描述：LoginController 类的用途
 * 日期：2024/12/17
 */
@Slf4j
@Controller
public class LoginController {
    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone)
    {
        //TODO 没输入手机号也能发验证码
        String uuid = UUID.randomUUID().toString(); // 生成标准 UUID
        String numericUuid = uuid.replaceAll("[^0-9]", ""); // 移除所有非数字字符
        String code = "1234"; // 控制长度，避免过长


        //1.接口放刷

        //2.验证码再次校验
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode))
        {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis()-l < 60000)
            {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code+"_"+System.currentTimeMillis(),10, TimeUnit.HOURS);

        thirdPartyFeignService.sendCode(phone,code);
        return R.ok();
    }


    /**
     * 注册
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String register(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes)
    {
        if (result.hasErrors())
        {
            Map<String,String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //1.验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s) || true)
        {
            if (true)
            //if (code.equals(s.split("_")[0]))
            {

                //redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证通过 调用远程服务注册
                R r = memberFeignService.regist(vo);
                if (r.getCode()==0)
                {
                    return "redirect:http://auth.gulimall.com//login.html";
                }
                else
                {
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg",r.getData(new TypeReference<String>(){}));
                    System.out.println("1111111");
                    System.out.println(r.getCode());
                    System.out.println(errors.toString());
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }
            else
            {
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }
        else
        {
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }


    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session)
    {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null)
            return "login";
        else
            return "redirect:http://gulimall.com";
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session)
    {
        //远程调用登录
        R r = memberFeignService.login(vo);
        if (r.getCode()==0)
        {
            MemberRespVo loginUser = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,loginUser);
            return "redirect:http://gulimall.com";
        }
        else
        {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
       
    }
}
